//
//  PayFaildJumpVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/22.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "PayFaildJumpVC.h"
#import "PayJumpTopCell.h"
#import "PayJumpListCell.h"
#import "PayJumpBottomView.h"
#import "PayJumpDateModel.h"
#import "PaySuccessJumpVC.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "PaymentRecordVC.h"
#import "NoHightTableCell.h"
@interface PayFaildJumpVC ()
@property (nonatomic, weak) PayJumpBottomView *footerView;

@property (nonatomic, strong) PayJumpDateModel *dataModel;

@property (nonatomic, strong) NSString *payType;
@end

@implementation PayFaildJumpVC

- (PayJumpBottomView *)footerView{
    
    if (!_footerView) {
        
        PayJumpBottomView *temp = (PayJumpBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([PayJumpBottomView class]) owner:nil options:nil].firstObject;

        [temp.leftBtn addTarget:self action:@selector(cancelDidBap) forControlEvents:UIControlEventTouchUpInside];
        
        [temp.rightBtn addTarget:self action:@selector(gotoPay) forControlEvents:UIControlEventTouchUpInside];

        
        _footerView = temp;
        
        _footerView.hidden = YES;
        
        [self.view addSubview:temp];
        
    }
    
    return _footerView;
}


- (void)gotoPay{
    
    
    
    MJWeakSelf;
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:@"选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [contr addAction:action0];
    
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"1";
        
        [weakSelf wachatPay];
        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"2";
        
        [weakSelf alipayPayWith];
        
    }];
    
    
    
    [contr addAction:action1];
    [contr addAction:action2];
    
    
    [self presentViewController:contr animated:YES completion:nil];
    
    
    
    
}



- (void)alipayPayWith{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = self.dataModel.pay_rmb;
    parameters[@"out_trade_no"] = self.dataModel.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                //                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}


- (void)wachatPay{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = self.dataModel.pay_rmb;
    parameters[@"out_trade_no"] = self.dataModel.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            //            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}




- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"缴费失败";
    
    [self setNav];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.estimatedRowHeight = 800;
    
    self.tableView.tableFooterView = self.footerView;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PayJumpTopCell class]) bundle:nil] forCellReuseIdentifier:[PayJumpTopCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PayJumpListCell class]) bundle:nil] forCellReuseIdentifier:[PayJumpListCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NoHightTableCell class]) bundle:nil] forCellReuseIdentifier:[NoHightTableCell identifierStr]];
    
    MJWeakSelf
    self.tableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.tableView.mj_header beginRefreshing];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];
    
}




- (void)WXApiDidSuccessNotification{
    
    PaySuccessJumpVC *jump = [[PaySuccessJumpVC alloc]init];
    
    jump.order_id = self.dataModel.out_trade_no;
    
    [self.navigationController pushViewController:jump animated:NO];


    
}

- (void)WXApiDidFailNotification{
    

    
    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
}

- (void)AlipayDidSuccessNotification{
    
    
    PaySuccessJumpVC *jump = [[PaySuccessJumpVC alloc]init];
    
    jump.order_id = self.dataModel.out_trade_no;

    [self.navigationController pushViewController:jump animated:NO];

    
}


- (void)AlipayDidFailNotification{
    
    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}







- (void)setNav{
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
    
    [but addTarget:self action:@selector(cancelDidBap) forControlEvents:UIControlEventTouchUpInside];
    
    
    but.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //        but.backgroundColor = [UIColor redColor];
    
    but.frame = CGRectMake(0, 0, 44, 44);
    but.contentEdgeInsets = UIEdgeInsetsMake(11, -10, 11, 22);
    
    UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc]initWithCustomView:but];
    
    self.navigationItem.leftBarButtonItem = returnButtonItem;
    
    
}


- (void)cancelDidBap{
    
//    PaymentRecordVC
    
    BOOL have = NO;
    
    for (UIViewController *temp in self.navigationController.childViewControllers) {
        if ([temp isKindOfClass:[PaymentRecordVC class]]) {
            have = YES;
        }
    }
    
    if (have == YES) {
        [self.navigationController popViewControllerAnimated:YES];

    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];

    }
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    
    
    
}

- (void)loadData{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    
    parameters[@"out_trade_no"] = self.order_id;

    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/orderDetail" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            MYJSONSTR
            //
//                                [responseObject[@"data"]  propertyCode];
            
            
            
            weakSelf.dataModel =  [PayJumpDateModel mj_objectWithKeyValues:responseObject[@"data"]];
            
            weakSelf.footerView.hidden = NO;
 
            //            weakSelf.bottomView.hidden = NO;
            //
            //            weakSelf.bottomView.model = weakSelf.dataModel;
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [weakSelf.tableView reloadData];
           
            
            
            
        } else {
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.dataModel == nil) {
         return 0;
    } else {
         return 2;
    }
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataModel == nil) {
        return 0;
    } else {
        
        if (section == 0) {
            return 1;
        } else {
            if ([self.dataModel.type isEqualToString:@"0"]) {
                return 7;
            } else if ([self.dataModel.type isEqualToString:@"1"]){
                return 7;
            }else{
                return 7;
                
            }
        }
        
        
        
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        PayJumpTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[PayJumpTopCell identifierStr]];
        
        tableCell.type = @"fail";
        
        return tableCell;
    } else {
        
        if ([self.dataModel.type isEqualToString:@"2"]) {
            
            if (indexPath.row == 6) {
                NoHightTableCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[NoHightTableCell identifierStr]];
                
                return tableCell;
                
            } else {
                PayJumpListCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[PayJumpListCell identifierStr]];
                
                tableCell.index = indexPath;
                
                tableCell.model = self.dataModel;
                
                return tableCell;
            }
            
        } else {
            
            if (indexPath.row == 6) {
                
                NoHightTableCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[NoHightTableCell identifierStr]];
                
                return tableCell;
                
            } else {
                PayJumpListCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[PayJumpListCell identifierStr]];
                
                tableCell.index = indexPath;
                
                tableCell.model = self.dataModel;
                
                return tableCell;
            }
            
        }
        
      
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    if (section == 0) {
        return 0.00001;
    } else {
        return 12;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 0.00001;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [[UIView alloc]init];
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *temp = [[UIView alloc]init];
    
    
    temp.backgroundColor = viewBgGrey;
    
    
    
    return temp;
    
    
    
    
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
